package com.zy.rpc.consumer.handle;

import com.zy.rpc.common.ask.RpcRequest;
import com.zy.rpc.common.ask.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * @author zy
 * @date 2023/5/7 16:15
 */

@Slf4j
public class RpcClientHandle extends SimpleChannelInboundHandler<RpcResponse> {
    private CompletableFuture<RpcResponse> future;

    public RpcClientHandle(CompletableFuture<RpcResponse> future) {
        this.future = future;
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        future.completeExceptionally(cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception {
        if (rpcResponse instanceof RpcResponse) {
            future.complete((RpcResponse) rpcResponse);
        } else {
            future.completeExceptionally(new IllegalArgumentException("Unexpected response type: " + rpcResponse.getClass().getName()));
        }
    }
}
